<script setup lang="ts">

import { ref, onMounted, watch } from 'vue';
import { Api } from '../../assets/api';
import type { HotWordData, DocsList } from '../../typings'
import { useRouter, useRoute } from 'vue-router';
import SearchCommodityComp from '../../components/SearchComps/SearchCommodity.vue';
import LoadingComp from '@/components/LoadingComp/LoadingComp.vue';
const router = useRouter()
const route = useRoute()

watch(() => route.query.text, (n) => {
    console.log(n);
    searchVal.value = n as string
    searchCommodity()
})


// 是否展示价格的下拉框
const isDown = ref(false);
// 搜索框值
const searchVal = ref('')
// 热门词条列表
const hotWord = ref<HotWordData>()
// 是否显示热门搜索和搜索历史
const isShowHistory = ref(true)
// 获取热门词条列表
const getHotData = async () => {
    let { data } = await Api.getHotSearchList()

    hotWord.value = data.data.hotWord
    console.log(hotWord.value);


}

let history = ref()

// 设置搜索框值
const setSearchVal = (kw: string) => {
    searchVal.value = kw
    searchCommodity(kw)
}

// 搜索结果
const commodityData = ref()

let page = ref(1)
let sort = ref('pop')
let minPrice = ref(0)
let maxPrice = ref(1000)


// 当前商品列表 用来做下拉加载
const currentCommodity = ref<Array<DocsList>>([])
// navbar高亮
const activeNav = ref(0)
// 筛选标题
const filterNav = ref()

// 搜索方法
const searchCommodity = async (kw = searchVal.value, pageVal = page.value, sortVal: string = sort.value, minPriceVal = minPrice.value, maxPriceVal = maxPrice.value) => {

    let arr = localStorage.historySearch ? JSON.parse(localStorage.historySearch) : []
    arr = arr.filter((item: {
        id: number,
        text: string
    }) => item.text != kw)
    arr.unshift({
        text: kw,
        id: Date.now()
    })

    history.value = history.value.filter((item: {
        id: number,
        text: string
    }) => item.text != kw)
    history.value.unshift({
        text: kw,
        id: Date.now()
    })

    localStorage.historySearch = JSON.stringify(arr)

    isShowHistory.value = false
    commodityData.value = ''
    currentCommodity.value = []
    isDown.value = false

    let { data } = await Api.getSearchList(
        kw,
        pageVal,
        sortVal,
        minPriceVal,
        maxPriceVal,

    )
    currentCommodity.value = data.result.wall.docs

    if (!filterNav.value) {
        filterNav.value = data.result.sortFilter
    }


    commodityData.value = data.result

    // console.log(commodityData.value);
    console.log(currentCommodity.value);
    // console.log(filterNav.value);

}

// 筛选商品
const changesNav = (sortKey: string, index: number) => {
    activeNav.value = index
    sort.value = sortKey
    searchCommodity(searchVal.value, page.value, sort.value)
}
const changesPrice = (min: number = minPrice.value, max: number = maxPrice.value) => {
    minPrice.value = min
    maxPrice.value = max
    searchCommodity(searchVal.value, page.value, sort.value, minPrice.value, maxPrice.value)
}

onMounted(() => {
    getHotData()

    history.value = localStorage.historySearch ? JSON.parse(localStorage.historySearch) : []


    searchVal.value = route.query.text as string
    
    if (searchVal.value) {
        searchCommodity()
    }
})

// 下拉商品加载
const roll = ref()
// 是否下拉加载
const isDropDown = ref(false)

const dropDownFn = async (kw = searchVal.value, pageVal = 1) => {
    let { data } = await Api.getSearchList(
        kw,
        pageVal,

    )

    data.result.wall.docs.map((item) => {
        currentCommodity.value.push(item)
    })
    isDropDown.value = false
}

const commodityScroll = () => {

    if (roll.value.scrollTop > 5600 * page.value) {
        isDropDown.value = true
        console.log(roll.value.scrollTop);
        page.value += 1
        dropDownFn(searchVal.value, page.value)
    }

}

const delHistory = ()=>{
    history.value = []
    localStorage.historySearch = history.value
}
</script>

<template>
    <div class="search-view ">
        <div class="nav w-full flex items-center sticky left-0 top-0 p-1">
            <van-icon name="arrow-left" size="25" @click="router.go(-1)" />

            <van-search shape="round" @focus="isShowHistory = true" class="w-4/5 mx-1" v-model.trim="searchVal"
                placeholder="请输入搜索关键词" />
            <span class="ml-1 font-bold" @click="searchCommodity()">
                <span v-show="isShowHistory"> 搜索</span>
                <van-icon v-show="!isShowHistory" name="cart-o" size="25" color="#afafaf" />
            </span>
        </div>

        <!-- 历史记录 -->
        <div class="history" v-show="isShowHistory">

            <div class="title flex justify-between items-center text-base">
                <div class="left">
                    <van-icon name="search" />
                    <span>历史搜索</span>
                </div>
                <van-icon @click="delHistory"  name="delete-o" size="20" />
            </div>

            <div class="search-history-list mt-2">

                <ul class="flex flex-wrap p-3">
                    <li @click="setSearchVal(h.text)" v-for="h in history" :key="h.id">{{ h.text }}</li>
                </ul>

            </div>


        </div>

        <!-- 热门搜索 -->
        <div class="hot-search" v-show="isShowHistory">

            <div class="hot-top p-3">
                <van-icon name="star-o" />
                <span class="ml-1">热门搜索</span>
            </div>

            <div class="hot-list">

                <ul class="flex flex-wrap px-3 p-2 justify-between">
                    <li @click="setSearchVal(h.frontword)" :style="{ color: h.color }" v-for="(h, i) in hotWord?.data"
                        :key="i">
                        {{ h.frontword }}
                    </li>
                </ul>

            </div>
            <van-skeleton title :row="3" v-show="!hotWord" />

        </div>

        <!-- 搜索结果列表 -->
        <div class="commodity-list text-black relative" v-show="!isShowHistory">

            <div class="title-nav relative px-2 bg-white" v-show="commodityData && filterNav">
                <!-- 筛选标题 -->
                <ul class="flex justify-between py-3 items-center ">
                    <li @click="changesNav(c.sortKey, i)" :class="{ 'active-li': activeNav == i }"
                        v-for="(c, i) in filterNav" :key="c.sortKey">
                        {{ c.title }}
                    </li>

                    <li @click="isDown = !isDown" :class="{ 'active-li': isDown }">
                        价格
                        <van-icon v-show="!isDown" name="arrow-down" />
                        <van-icon v-show="isDown" name="arrow-up" />
                    </li>
                </ul>
                <!-- 价格的筛选 -->
                <div v-show="isDown"
                    class="price-filter w-full py-4  text-sm mt-2 font-thin absolute -bottom-24 bg-white pr-5 z-10">


                    <div class="filter-top flex justify-between  pr-3">

                        <div @click="changesPrice(p.min, p.max)" class="px-6 py-0.5 bg-gray-100"
                            v-for="(p, i) in commodityData?.priceFilter" :key="i">
                            {{ p.min }} - {{ p.max }}
                        </div>

                    </div>

                    <div class="filter-botton flex justify-between items-center mt-3 ">
                        区间(元) <input v-model="minPrice" class=" border w-20 h-8 " type="text"> <b>---</b> <input
                            v-model="maxPrice" class=" border w-20 h-9 " type=""> <span
                            class="px-7  h-8 bg-red-500 text-gray-100 font-medium text-center leading-9 "
                            @click="changesPrice()">确认</span>
                    </div>

                </div>
            </div>



            <!-- 商品列表 -->
            <div ref="roll" @scroll="commodityScroll" class="sp-list bg-gray-100 pb-3">
                <van-cell class="p-2 pt-0 bg-gray-100">

                    <div class="flex w-full h-full flex-wrap justify-between">
                        <div class="w-44" v-for="item in currentCommodity" :key="item.tradeItemId">
                            <SearchCommodityComp :list="item"></SearchCommodityComp>
                        </div>
                    </div>
                </van-cell>

                <van-empty v-show="currentCommodity.length == 0"
                    image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png" image-size="80"
                    description="找不到商品" />

                <div class=" text-center">
                    <van-loading v-show="isDropDown" />
                </div>

            </div>
            <van-back-top target=".sp-list" bottom="20vh" />

            <LoadingComp :type="2" v-show="!commodityData"></LoadingComp>


        </div>

    </div>
</template>


<style lang="scss" scoped>
.search-view {
    width: 100vw;
    height: 100vh;
    position: fixed;
    left: 0;
    top: 0;
    background-color: #fff;
    color: #c3aca6;
    z-index: 10;


    .history {
        padding: 10px;
        border-top: 1px solid rgba(216, 201, 197, .5);
        border-bottom: 1px solid rgba(216, 201, 197, .5);
        min-height: 15vh;
    }

    .search-history-list,
    .hot-list {
        ul {
            width: 100%;

            li {
                margin: 0 8px;
                font-size: 14px;
                color: #000;
                border: 1px solid rgba(216, 201, 197, .3);
                border-radius: 5px;
                padding: 6px;
            }
        }
    }

    .commodity-list {
        border-top: 1px solid #ccc;

        .title-nav {

            ul {

                li {

                    flex: 0 0 23%;
                    text-align: center;
                    border-right: 1px solid #ccc;
                    line-height: 14px;
                    font-size: 14px;

                    &.active-li {
                        color: tomato;
                    }

                    &:last-child {
                        border: none;
                    }
                }
            }
        }
    }

    .sp-list {
        height: 85vh;
        padding-bottom: 30px;
        overflow-y: auto;

        &::-webkit-scrollbar {
            display: none;
        }

        .text-center {
            min-height: 30px;
        }
    }
}
</style> 